import { memo, useEffect } from "react";
import { View, Text } from "@tarojs/components";
import { useReachBottom, useLoad } from "@tarojs/taro";
import { useAppSelector, useAppDispatch, shallowEqualApp } from "@/store/index";
import {
  getHomeInfoAction,
  getRecommendAction,
  getGoodsAction,
  setCurrentTab,
  tabs,
} from "@/store/modules/home";
import TabControl from "@/components/tab-control";
import GridView from "@/components/grid-view";

import HomeSearch from "./cpns/home-search/index";
import HomeBanner from "./cpns/home-banner/index";
import HomePopular from "./cpns/home-popular";
import HomeRecommend from "./cpns/home-recommend";

import style from "./index.module.scss";

const Home = () => {
  const { banners, populars, recommend, goodsList, currentTab } =
    useAppSelector(
      (state) => ({
        banners: state.home.banners,
        populars: state.home.populars,
        recommend: state.home.recommend,
        currentTab: state.home.currentTab,
        goodsList: state.home.goodsList,
      }),
      shallowEqualApp
    );

  const dispatch = useAppDispatch();
  useLoad(() => {
    dispatch(getHomeInfoAction());
    dispatch(getRecommendAction());
    dispatch(getGoodsAction({ type: 0, page: 1 }));
    dispatch(getGoodsAction({ type: 1, page: 1 }));
  });
  function hadnleTabClick(index) {
    // 切换显示
    dispatch(setCurrentTab(tabs[index]));
  }

  // 获取下一页数据
  useReachBottom(() => {
    // currentTab = specific  single
    const currentType = currentTab === tabs[0] ? 0 : 1;
    const nextPage = goodsList[currentTab].page + 1;
    dispatch(getGoodsAction({ type: currentType, page: nextPage }));
  });

  return (
    <View className={style["home"]}>
      <HomeSearch></HomeSearch>
      <HomeBanner banners={banners}></HomeBanner>
      <HomePopular populars={populars}></HomePopular>
      {recommend && <HomeRecommend recommend={recommend}></HomeRecommend>}
      <TabControl
        tabs={["精选专场", "精选单品"]}
        onTabClick={hadnleTabClick}
      ></TabControl>
      <GridView goods={goodsList[currentTab].list}></GridView>
    </View>
  );
};

export default memo(Home);
